package net.codesree.web;

import java.io.IOException;

import javax.sql.DataSource;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.codesree.action.IAction;
import net.codesree.utils.Configuration;

public abstract class AbstractActionController extends HttpServlet {

 protected ServletContext application=null;
 private DataSource dSource=null;
 protected IAction defaultAction=null;
 protected Configuration configuration=null;
 
 public void init(ServletConfig config) {
  this.application=getServletContext();
  String urlEnding=config.getInitParameter("urlEnding");  
  this.configuration=Configuration.getConfiguration(urlEnding,dSource);
  this.application.setAttribute("CONFIGURATION",configuration);
  mapUrls();
  setDefaultAction();
 }

 public void service(HttpServletRequest req,HttpServletResponse res) throws
   IOException,ServletException {
   IAction action=getAction(req);
   if(null==action) {
	action=getDefaultAction();   
   }
   action.execute(application,req,res);   
 }
 public abstract IAction getDefaultAction();
 public abstract void setDefaultAction();
 public abstract void mapUrls();
 public abstract IAction getAction(HttpServletRequest req);
 //Need to mend this
 protected void configureDataSource(String dSourceName) {
  try {
	Context ctx=new InitialContext();
	this.dSource=(DataSource) ctx.lookup("java:comp/env/jdbc/"+dSourceName);
  } catch(NamingException nex) {
	System.err.println("DataSource not configured..."+nex.getMessage());
	nex.printStackTrace();
  }
 }
}
